#include "fruit.h"
#include<QIcon>
#include<QPainter>
#include<QPixmap>
#include"basket.h"
#include<QMouseEvent>
#include<QApplication>
#include<QCursor>
#include<QPoint>
#include<QDebug>
#include"stats.h"
#include<ctime>
fruit::fruit(QWidget *parent)
    : QWidget(parent)
{
    initfruit();
    QCursor cursor;
    cursor.setShape(Qt::OpenHandCursor);
    setCursor(cursor);
    startit();
}

fruit::~fruit()
{

}
void fruit::initfruit()
{

   this->setGeometry(QRect(800,50,552,954));
    setWindowTitle("接水果");
    setWindowIcon(QIcon(":/tu/WPS图片-修改尺寸"));
    l_timer.setInterval(l_rate);//设置定时器
    l_time2=0;
    srand((unsigned int)time(nullptr));
}
void fruit::paintEvent(QPaintEvent *)
{
    QPainter p;
    p.begin(this);

    p.drawPixmap(0,0,map2.map1);
    p.end();
    //画蓝子
    QPainter t;
    t.begin(this);
    t.drawPixmap(x1-500,z+100,bask_k.bask);

    for(int i=0;i<l_num;i++){
        if(l_fruits[i].l_ok==false){
            t.drawPixmap(l_fruits[i].l_x,l_fruits[i].l_y,l_fruits[i].l_fruit);

        }
    }
    t.end();
}

void fruit::fruitshow()
{
   l_time2++;
   if(l_time2<l_time)
   {
     return;
   }
   l_time2=0;
   for(int i=0;i<20;i++)
   {
       if(l_fruits[i].l_ok){
           l_fruits[i].l_ok=false;
           l_fruits[i].l_x=rand()%(552-l_fruits[i].l_rect.width());
           l_fruits[i].l_y=-l_fruits[i].l_rect.height();
           break;
       }
   }
}

void fruit::startit()
{
    l_timer.start();
    //接收信号
    connect(&l_timer,&QTimer::timeout,
            [=](){

        update();
        fruitshow();
        updatepos();
    });

}

void fruit::updatepos()
{
    for(int i=0;i<l_num;i++){
        if(l_fruits[i].l_ok==false){
            l_fruits[i].updateposition();

        }
    }
}



void fruit::mousePressEvent(QMouseEvent *event)
{
    if(event->button()==Qt::LeftButton){
        QCursor cursor;
        cursor.setShape(Qt::ClosedHandCursor);
        QApplication::setOverrideCursor(cursor);
        offset=event->globalPos()-pos();

    }
    else if (event->button()==Qt::RightButton){

    }
}

void fruit::mouseMoveEvent(QMouseEvent * event)
{
if(event->buttons()&Qt::LeftButton){
    QPoint temp;
    temp=event->globalPos()-offset;

    x1=temp.rx();
    z=temp.ry();

 bask_k.setposition(x1,z);


 bask_k.bask.copy(bask_k.b_rect);

}

}

